package com.pushdeer;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * author: liuchangrong
 * date: 2022-02-24 23:30
 * description: 封装发送消息的客户端
 */
public class PushDeerClient {

    private Logger logger = LoggerFactory.getLogger(PushDeerClient.class);
    /**
     * pushdeer服务端地址
     */
    private String host = "https://api2.pushdeer.com";

    /**
     * 发送消息路由
     */
    private String pushMsgPath = "/message/push";

    /**
     * 发送消息所需要的key
     */
    private String pushMessageKey;

    /**
     * 初始化必须指定发送消息所需要的key
     * @param pushKey
     */
    public PushDeerClient(String pushKey) throws Exception{
        if(pushKey == null || pushKey.length() == 0){
            logger.error("PushDeer send message key cannot be configured with empty string");
            throw new Exception("send message key cannot be empty");
        }
        pushMessageKey = pushKey;
    }

    /**
     * 设置自己搭建的服务器的地址
     * @param selfHost
     */
    public void setHost(String selfHost) throws Exception {
        if(selfHost == null || selfHost.length() == 0){
            logger.error("PushDeer host cannot be configured with empty string");
            throw new Exception("PushDeer host cannot be empty");
        }
        host = selfHost;
    }

    /**
     * 请求具体的发送消息地址，根据返回的响应判断是否发送成功
     * @param url
     * @return
     */
    private boolean isSendMessageSuccess(String url){
        try {
              String response = RequestUtil.sendRequest(url);
            if(response == null || response.length() == 0){
                return false;
            }
            RequestResponse dto = JSONObject.parseObject(response, RequestResponse.class);
            if(dto != null){
                // 发送消息成功
                if(dto.getCode() == 0){
                    return true;
                }
                logger.error("send message error: "+ dto.getError());
            }
            return false;
        } catch (IOException e) {
            logger.error("request pushdeer host error: "+ e.getMessage());
            return false;
        }
    }

    /**
     * 发送文字消息
     * @param text
     */
    public void sendTextMessage(String text, String desp) throws UnsupportedEncodingException {
        pushMessage(text,desp,"text",pushMessageKey);
    }

    /**
     * 发送markdown消息
     * @param text
     * @param desc
     */
    public void sendMarkDownMessage(String text, String desc) throws UnsupportedEncodingException {
        pushMessage(text, desc, "markdown", pushMessageKey);
    }

    /**
     * 发送图片消息
     * @param imageSrc 可以是图片的链接或者是base64,但如果是base64建议使用post进行传输
     * @param desc
     */
    public void sendImageMessage(String imageSrc, String desc) throws UnsupportedEncodingException {
        pushMessage(imageSrc, desc, "image", pushMessageKey);
    }


    /**
     * 实际发送消息
     * @param text 推送消息内容
     * @param desp 消息内容第二部分
     * @param type 消息类型 文本=text，markdown，图片=image
     * @param pushMessageKey PushKey
     */
    private void pushMessage(String text, String desp, String type, String pushMessageKey)
            throws UnsupportedEncodingException {
        String sendUrl = host+pushMsgPath+"?text="+ URLEncoder.encode(text, "utf-8")+"&desp="+
                URLEncoder.encode(desp, "utf-8")+"&type="+type+"&pushkey="+pushMessageKey;
        boolean isSuccess = isSendMessageSuccess(sendUrl);
        if(isSuccess){
            logger.debug("message send success!");
        }else{
            logger.error("message send fail");
        }
    }

}
